package com.qby.common.utils;


import com.qby.common.exceptions.LoginException;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * @description: 当前登录用户
 * @author: qiu bo yang
 * @create: 2020-03-26 09:53
 */
public class SecurityUtils {
    private static final String UserId = "userId";
    public static final String Token = "token";

    public static Integer getUserId() {
        String userId = getAttribute(UserId);
        if (userId == null) {
            throw new LoginException("登录已失效,请重新登录");
        }
        return Integer.valueOf(userId);
    }

    public static String getAttribute(String key) {
        Object o = getRequest().getAttribute(key);
        return null == o ? null : String.valueOf(o);
    }

    public static Integer setUserId(Integer userId) {
        setAttribute(UserId, userId);
        return userId;
    }

    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static void setAttribute(String key, Object value) {
        getRequest().setAttribute(key, value);
    }

    public static String getToken() {
        return getRequest().getHeader(Token);
    }
}
